package com.java.sample.domain;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AdJnaInfoServiceImpl implements IAdInfoService {

    // 定义必要的常量
    private static final int NET_SETUP_WORK_GROUP_NAME = 2;
    private static final int NetSetupDomainName = 3;

    @Override
    public String getUserName(){
        return Advapi32Util.getUserName();
    }

    @Override
    public String getComputerName() {
        // 方法1: 使用 Kernel32 API
        char[] buffer = new char[WinBase.MAX_COMPUTERNAME_LENGTH + 1];
        IntByReference lpnSize = new IntByReference(buffer.length);

        if (Kernel32.INSTANCE.GetComputerName(buffer, lpnSize)) {
            return new String(buffer, 0, lpnSize.getValue());
        }

        // 方法2: 环境变量回退
        return System.getenv(CommonConsts.PROP_WIN_COMPUTER_NAME);
    }

    @Override
    public String getDomain(){
        // 方法1: 从用户名中提取
        String userName = getUserName();
        if (userName.contains("\\")) {
            return userName.split("\\\\")[0];
        }

        // 方法2: 使用NetAPI32
        PointerByReference ptr = new PointerByReference();
        IntByReference joinType = new IntByReference();

        int result = Netapi32.INSTANCE.NetGetJoinInformation(null, ptr, joinType);
        if (result == 0) {
            try {
                switch (joinType.getValue()) {
                    case NetSetupDomainName:
                        // 正确的域名提取方式
                        Pointer p = ptr.getValue();
                        // 读取前4个字节获取字符串指针
                        Pointer namePointer = p.getPointer(0);
                        // 读取以null结尾的宽字符字符串
                        return namePointer.getWideString(0);
                    case NET_SETUP_WORK_GROUP_NAME:
                        // 工作组
                        return "";
                    default:
                        return "";
                }
            } finally {
                Netapi32.INSTANCE.NetApiBufferFree(ptr.getValue());
            }
        }

        // 方法3: 环境变量回退
        return System.getenv(CommonConsts.PROP_DOMAIN);
    }

}